<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="品牌编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入品牌编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="厂家编码" prop="manufacturerCode">
        <el-input
          v-model="queryParams.manufacturerCode"
          placeholder="请输入厂家编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
<!--      <el-form-item label="厂家名称" prop="manufacturerName">-->
<!--        <el-input-->
<!--          v-model="queryParams.manufacturerName"-->
<!--          placeholder="请输入厂家名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <!-- <el-form-item label="所属厂家" prop="manufacturer">
        <el-select
          v-model="queryParams.manufacturer"
          value-key="code"
          placeholder="所属厂家"
          clearable
          size="small"
          style="width: 240px"
          @change="mauChange"
        >
          <el-option
            v-for="mau in manufacturers"
            :key="mau.code"
            :label="mau.name"
            :value="mau"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:brand:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:brand:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:brand:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['device:brand:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:brand:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品牌编码" align="center" prop="code" width="190"/>
      <el-table-column label="品牌名称" align="center" prop="name" />
      <!-- <el-table-column label="厂家编码" align="center" prop="manufacturerCode" /> -->
<!--      <el-table-column label="厂家名称" align="center" prop="manufacturerName" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:brand:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:brand:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" @open="openE" @close="closeE" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="品牌编码" prop="code" v-if="form.id">
          <el-input v-model="form.code" disabled />
        </el-form-item>
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
<!--        <el-form-item label="所属厂家" prop="manufacturer">-->
<!--          <el-select-->
<!--            v-model="form.manufacturer"-->
<!--            value-key="code"-->
<!--            placeholder="所属厂家"-->
<!--            clearable-->
<!--            @change="changeSelect($event)"-->
<!--          >-->

<!--        <div v-for="mau in deManufacturers" :key="mau.code">-->
<!--            <el-tooltip  effect="dark" content="已停用" placement="top-start">-->
<!--              <el-option disabled-->
<!--                :key="mau.code"-->
<!--                :label="mau.name"-->
<!--                :value="mau"-->
<!--              />-->
<!--            </el-tooltip>-->
<!--          </div>-->

<!--          &lt;!&ndash; <el-option disabled v-for="mau in deManufacturers"-->
<!--            :key="mau.code"-->
<!--            :label="mau.name"-->
<!--            :value="mau"-->
<!--          /> &ndash;&gt;-->
<!--          <el-option-->
<!--            v-for="mau in manufacturers"-->
<!--            :key="mau.code"-->
<!--            :label="mau.name"-->
<!--            :value="mau"-->
<!--          />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  删除模块失败提示-->
    <el-dialog
      :visible.sync="deleteFailedDialogVisible"
      top="100px !important"
      width="800px"
      :close-on-click-modal="false"
      z-index="1002"
    >
      <template slot="title">
        提示：<span class="tip" style="color: red;">品牌被以下模块和设备引用，若要删除，请先从模块管理或设备管理界面解绑模块对应的品牌！</span>
      </template>

      <el-tabs v-model="activeInUseTab">
        <el-tab-pane label="设备引用列表" name="deviceList" v-if="brandInUsedData.unbindDevices">
          <deviceInUsedList :list="brandInUsedData.unbindDevices" @close-dialog="deleteFailedDialogVisible = false"/>
        </el-tab-pane>
        <el-tab-pane label="模块引用列表" name="modelList" v-if="brandInUsedData.unbindModules">
          <modelInUsedList :list="brandInUsedData.unbindModules" @close-dialog="deleteFailedDialogVisible = false"/>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteFailedDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <import-file-dialog
      v-model="uploadDialogVisible"
      templateFileName="品牌信息导入模板"
      uploadApi="/device/brand/import"
      templateDownloadUrl="/device/brand/export"
      @onSuccess="handleUploadFileSuccess"
    />
  </div>
</template>

<script>
import { listBrand, getBrand, delBrand, addBrand, updateBrand } from "@/api/device/brand";
import modelInUsedList from './components/modelInUsedList';
import deviceInUsedList from './components/deviceInUsedList';

export default {
  name: "Brand",
  dicts: ['sys_normal_disable'],
  components:{
    modelInUsedList,
    deviceInUsedList
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品牌表格数据
      brandList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      //停用的厂家
      deManufacturers: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
        manufacturerCode: null,
        manufacturerName: null,
        manufacturer: null,
        status: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
      },
      deleteFailedDialogVisible: false,
      brandInUsedData:{},
      activeInUseTab: "deviceList",
      uploadDialogVisible: false
    };
  },
  created() {
    // 提前加载厂家数据保存到vuex
    this.$store.dispatch('LoadManufacturersCache');
    this.getList();
  },
  computed: {
    //有效的厂家，用于下拉列表
    manufacturers(){
      return this.$store.state.device.manufacturers || []
    }
  },
  methods: {
    // 导入文件上传成功
    handleUploadFileSuccess(res) {
      if (res.data === "上传成功！") this.getList()
    },
    handleImport() {
      this.uploadDialogVisible = true
    },
    /**厂家下拉列表更改 */
    changeSelect(selection) {
      this.form.manufacturerCode = selection.code;
      this.form.manufacturerName = selection.name;
    },

     //对话框打开时的回调函数
    openE(){},

    //对话框关闭是的回调函数
    closeE(){
      this.reset();
      this.deManufacturers = [];
    },


    //  /**查询条件厂家下拉列表更改 */
    // mauChange() {
    //   console.log(this.queryParams.manufacturer);
    // },

    /** 查询品牌列表 */
    getList() {
      this.loading = true;
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        manufacturerCode: null,
        manufacturerName: null,
        manufacturer: null,
        status: 0,//新增窗口打开时 状态默认正常
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品牌";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBrand(id).then(response => {
        this.manufacturers.forEach(element => {
          if(element.code === row.manufacturerCode){
            response.data.manufacturer = element;
          }
        })

        if(response.data.manufacturer === undefined){
            response.data.manufacturer = {code: response.data.manufacturerCode, name: response.data.manufacturerName};
            this.deManufacturers.push({code: response.data.manufacturerCode, name: response.data.manufacturerName});
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改品牌";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBrand(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('LoadBrandCache');
            });
          } else {
            addBrand(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$store.dispatch('LoadBrandCache');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$store.state.message.delConfirm).then(function() {
        return delBrand(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.$store.dispatch('LoadBrandCache');
      }).catch((res) => {
        this.loading = false;
        const _data = res.data;
        if (_data) {
          this.brandInUsedData = _data;
          // 设置激活tab
          this.activeInUseTab = _data.unbindDevices ? "deviceList" : "modelList";
          this.deleteFailedDialogVisible = true;
        }
        // console.log(list,'删除失败')
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('device/brand/export', {
        ...this.queryParams
      }, `品牌管理_${currentDate}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-select{
  width: 100%;
}
</style>
